package ai_bloomfilter

import (
	"net/http"
	"github.com/gin-gonic/gin"
	"fmt"
)

const (
	SUCCESS = 200
	NOT_FOUND = 201
	EXISTS = 202
	SERVER_ERROR = 503
	UN_SUPPORT = 404
)

type AIHandler struct {
	BloomFilter *AIBloomFilter
}

type AIResponse struct {
	Code 	int		`json:"code"`
	Message string	`json:"message"`
}

func (hd *AIHandler) Init(bloomFilter *AIBloomFilter) error {
	hd.BloomFilter = bloomFilter
	return nil
}

func (hd *AIHandler) Handler(context *gin.Context) {
	op := context.DefaultQuery("op", "add")
	key := context.DefaultQuery("key", hd.BloomFilter.Key)
	value := context.Query("value")
	resp := &AIResponse{}

	if op == "add" {
		exists, err := hd.BloomFilter.IsExists(key, value)
		if err != nil {
			resp.Code = SERVER_ERROR
			resp.Message = fmt.Sprintf("Server error [%v]", err.Error())
			context.JSON(http.StatusInternalServerError, resp)
			return
		}
		if exists {
			resp.Code = EXISTS
			resp.Message = fmt.Sprintf("[%s] has exists in key[%s]", value, key)
		} else {
			err = hd.BloomFilter.Add(key, value)
			if err != nil {
				resp.Code = SERVER_ERROR
				resp.Message = fmt.Sprintf("Server error [%v]", err.Error())
				context.JSON(http.StatusInternalServerError, resp)
				return
			}
			resp.Code = SUCCESS
			resp.Message = fmt.Sprintf("add %s into %s successfully", value, key)
		}
	} else if op == "remove" {
		exists, err := hd.BloomFilter.IsExists(key, value)
		if err != nil {
			resp.Code = SERVER_ERROR
			resp.Message = fmt.Sprintf("Server error [%v]", err.Error())
			context.JSON(http.StatusInternalServerError, resp)
			return
		}
		if !exists {
			resp.Code = NOT_FOUND
			resp.Message = fmt.Sprintf("[%s] is not exists in key[%s]", value, key)
		} else {
			err = hd.BloomFilter.Remove(key, value)
			if err != nil {
				resp.Code = SERVER_ERROR
				resp.Message = fmt.Sprintf("Server error [%v]", err.Error())
				context.JSON(http.StatusInternalServerError, resp)
				return
			}
			resp.Code = SUCCESS
			resp.Message = fmt.Sprintf("remove %s from %s successfully", value, key)
		}
	} else if op == "exists" {
		exists, err := hd.BloomFilter.IsExists(key, value)
		if err != nil {
			resp.Code = SERVER_ERROR
			resp.Message = fmt.Sprintf("Server error [%v]", err.Error())
			context.JSON(http.StatusInternalServerError, resp)
			return
		}
		if exists {
			resp.Code = SUCCESS
			resp.Message = fmt.Sprintf("%s exists in %s", value, key)
		} else {
			resp.Code = NOT_FOUND
			resp.Message = fmt.Sprintf("%s does not exists in %s", value, key)
		}
	} else {
		resp.Code = UN_SUPPORT
		resp.Message = fmt.Sprintf("op type %s is not supported", op)
	}
	context.JSON(http.StatusOK, resp)
}